package com.mab.mall.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mab.mall.search.config.MallElasticSearchConfiguration;
import com.mab.mall.search.service.ElasticSearchService;
import com.msb.common.constant.ElasticSearchConstant;
import com.msb.common.dto.es.SkuESModel;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 实现商品上架数据存储到ES中
     * @param skuESModelList
     */
    @Override
    public Boolean saveProduct(List<SkuESModel> skuESModelList) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel skuESModel : skuESModelList) {
            // ES添加操作，指定索引库
            IndexRequest indexRequest = new IndexRequest(ElasticSearchConstant.PRODUCT_UP);
            // 添加的id
            indexRequest.id(skuESModel.getSkuId().toString());
            // 添加的文档
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(skuESModel);
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        return !b;
    }
}
